import java.util.Arrays;

public class Main20250308 {


}

class Solution {
    public long maximumBeauty(int[] flowers, long newFlowers, int target, int full, int partial) {
        Arrays.sort(flowers);
        //从后往前计算一共需要多少个花能full
        long newFlower = newFlowers, fullNum = 0;
        for (int i = flowers.length - 1; i >= 0; i--) {
            if (flowers[i] >= target) {
                fullNum++;
            } else if (flowers[i] < target && newFlower >= target - flowers[i]) {
                fullNum++;
                newFlower -= target - flowers[i];
            } else {
                break;
            }
        }
        //newFlower 还剩多少花，fullNum 有多少花园是满的
        if (fullNum == flowers.length) {
            return full * fullNum;
        }
        //从前向后遍历 计算可以填充多少不满的花园
        int min = 0;
        for (int i = 1; i < flowers.length; i++) {
            if (newFlower > i * (flowers[i] - flowers[i - 1])) {
                newFlower -= i * (flowers[i] - flowers[i - 1]);
            } else if (newFlower == i * (flowers[i] - flowers[i - 1])) {
                min = flowers[i];
                break;
            } else {
                min = flowers[i - 1] + 1;
                break;
            }
        }
        return min * partial + full * fullNum;
    }
}
